<template>
  <div class="app-container">
    <el-row class="order-state-row">
      <el-col>
        <div>
          <span style="margin-right: 14px">售后状态</span>
          <el-radio-group
            v-model="queryParams.status"
            size="mini"
            @input="network().getList()"
          >
            <el-radio-button :label="undefined">全部</el-radio-button>
            <el-radio-button label="0">待审核</el-radio-button>
            <el-radio-button label="1">待寄件</el-radio-button>
            <el-radio-button label="2">待收件</el-radio-button>
            <el-radio-button label="4">退款成功</el-radio-button>
            <el-radio-button label="7">退款关闭</el-radio-button>
            <el-radio-button label="5">已取消</el-radio-button>
          </el-radio-group>
        </div>
        <div style="margin: 20px 0">
          <span style="margin-right: 14px">售后类型</span>
          <el-radio-group
            v-model="queryParams.returnType"
            size="mini"
            style="background: transparent !important"
            @input="network().getList()"
          >
            <el-radio-button :label="undefined">全部</el-radio-button>
            <el-radio-button label="1">仅退款</el-radio-button>
            <el-radio-button label="3">退货退款</el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
    </el-row>
    <dk-query
      ref="nxIB"
      :searchForm="queryParams"
      :inputList="inputList"
      :queryTable="click().handleQuery"
      labelWidth="110"
    >
    </dk-query>
    <dk-table
      ref="table"
      :column="column"
      :pagination="paginationObjs"
      :tableData="tableData"
      :height="tableHeight"
    >
    </dk-table>

    <!-- 审核弹窗 -->
    <el-dialog
      title="审核"
      :visible.sync="audit.auditDialog"
      width="30%"
      class="dialog-container"
      :before-close="closeDialog"
    >
      <el-form
        ref="dialogData"
        :rules="audit.dialogRules"
        label-suffix=":"
        :model="audit.dialogData"
      >
        <el-form-item prop="auditStatus" label="审核意见" label-width="90px">
          <el-select
            v-model="audit.dialogData.auditStatus"
            placeholder="请选择"
            size="mini"
          >
            <el-option label="通过" value="1"></el-option>
            <el-option label="驳回" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          label="退款金额"
          prop="refundRmb"
          label-width="90px"
        >
          <el-input
            placeholder="请输入金额"
            v-model="audit.dialogData.refundRmb"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="audit.dialogData.auditStatus == '1'"
          prop="remarkVal"
          label="备注"
          label-width="90px"
        >
          <el-input placeholder="请输入，最多100字" v-model="audit.remarkVal">
          </el-input>
        </el-form-item>
        <el-form-item
          prop="auditReason"
          label="驳回理由"
          label-width="90px"
          v-if="audit.dialogData.auditStatus == '2'"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入驳回理由,最多输入100字"
            v-model="audit.dialogData.auditReason"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="click().handleClose('dialogData')">取 消</el-button>
        <el-button type="primary" @click="click().handleStatus('dialogData')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 接口api：first step
import {
  getOrderList,
  examineOrder,
  comfirmOrder,
  exportOrder,
} from '@/api/merchant-order-manage/aftermarket-orders.js';
import { getStatusActions } from '@/utils/status.js';
export default {
  data() {
    var validateRmb = (rule, value, callback) => {
      if (+value > +this.payRmb) {
        callback(new Error('退款金额不能大于实付款金额'));
      }
      if (!value) {
        callback(new Error());
      } else {
        callback();
      }
    };
    return {
      loading: true,
      // 类型，1-商家配送，2-门店自提,3-会员服务
      type: 1,
      // 表格退款金额
      payRmb: '',
      // 快递配送 - 规程toolbar：two step
      inputList: [
        {
          type: 'input',
          placeholder: '请输入',
          label: '售后编号',
          name: 'returnNo',
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '订单编号',
          name: 'orderNo',
        },
        {
          type: 'daterange',
          placeholder: '选择日期',
          label: '创建时间',
          name: 'dateRange',
          fun: (row) => {
            this.queryParams.dateRange[0] = `${row[0]} 00:00:00`;
            this.queryParams.dateRange[1] = `${row[1]} 23:59:59`;
          },
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '商品名称',
          name: 'goodsName',
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '用户昵称',
          name: 'userNickName',
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '手机号',
          name: 'userPhone',
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '归属品牌',
          name: 'brand',
        },
        {
          type: 'common-button',
          isShowExport: true,
          hasPermissObj: {
            export: () => `${this.urlObject.permissPrefix}export`,
          },
          searchFun: (searchForm) => {
            this.queryParams = searchForm;
            this.click().handleQuery();
          },
          resetFun: () => {
            this.click().resetQuery();
          },
          exportFun: () => {
            this.click().handleExport();
          },
        },
      ],
      // 快递配送 - 规程表头：shree step
      column: [
        {
          value: 'returnNo',
          name: '售后编号',
        },
        {
          value: 'orderNo',
          name: '订单编号',
        },
        {
          value: 'goodsName',
          name: '商品名称',
        },
        {
          value: 'brandName',
          name: '归属品牌',
        },
        {
          value: 'userNickName',
          name: '用户昵称',
        },
        {
          value: 'userPhone',
          name: '手机号码',
        },
        {
          value: 'applyRmb',
          name: '退款金额',
        },
        {
          value: 'returnType',
          name: '售后类型',
          stateList: [
            { name: '仅退款', value: 1 },
            { name: '退货', value: 2 },
            { name: '退货退款', value: 3 },
          ],
        },
        {
          value: 'status',
          name: '售后状态',
          stateList: [
            { name: '待审核', value: 0 },
            { name: '待寄件', value: 1 },
            { name: '待收件', value: 2 },
            /* 售后订单列表没有退款中的状态 */
            // { name: '退款中', value: 3 },
            { name: '退款成功', value: 4 },
            { name: '已取消', value: 5 },
            { name: '退款失败', value: 6 },
            { name: '退款关闭', value: 7 },
          ],
        },
        {
          value: 'createTime',
          name: '创建时间',
        },

        {
          width: 120,
          value: 'id',
          name: '操作',
          fixed: 'right',
          type: 'button',
          buttonList: [
            {
              type: 'no-tooltip',
              name: '审核',
              fun: (row) => {
                this.click().handleAudit(row);
              },
              showFun: (row) => {
                return row.status == 0;
              },
              color: 'text',
            },
            {
              type: 'no-tooltip',
              name: '确认收件',
              fun: (row) => {
                this.click().handleComfirm(row);
              },
              showFun: (row) => {
                return getStatusActions(row.status).PickUp;
              },
              color: 'text',
            },
            {
              type: 'no-tooltip',
              name: '详情',
              fun: (row) => {
                this.click().handleDetail(row);
              },
              color: 'text',
              hasPermiss: () => `${this.urlObject.permissPrefix}detail`,
            },
          ],
        },
      ],
      // 快递配送 - 查询参数
      queryParams: { status: undefined, returnType: undefined },
      // 快递配送 - 表格数据
      tableData: [],

      // 审核弹窗对象
      audit: {
        remarkVal: '',

        // 审核弹出框
        auditDialog: false,
        // 审核弹出框弹出框内容
        dialogData: {
          auditReason: '',
          refundRmb: '',
          auditStatus: '',
          id: '',
        },
        // 对话框校验对象
        dialogRules: {
          auditStatus: [
            { required: true, message: '请选择审核意见', trigger: 'change' },
          ],
          refundRmb: [
            { required: true, message: '请输入退款金额', trigger: 'change' },
            {
              validator: validateRmb,
              required: true,
              message: '退款金额不能大于实付款金额',
              trigger: 'change',
            },
          ],
          auditReason: [
            {
              required: true,
              max: 100,
              message: '请输入驳回理由',
              trigger: 'blur',
            },
          ],
        },
      },
      // 分页器
      paginationObjs: {
        paginationChange: function () {
          this.network().getList(false);
        }.bind(this),
        page: 1,
        limit: 10,
        total: 0,
        loading: false,
      },

      // url对象：four step
      urlObject: {
        permissPrefix: 'order-manage:aftermarket-orders:',
        routePathPrefix: '/order-manage/AftermarketOrders/',
      },
      // 接口存储对象：five step
      interfaceObj: {
        getApiName: getOrderList,
        examineApiName: examineOrder,
      },
    };
  },

  created() {
    this.network().getList();
    this.getTableHeight.call(this);
  },
  methods: {
    closeDialog() {
      this.audit.auditDialog = false;
      this.$refs['dialogData'].resetFields();
      this.audit.dialogData.auditStatus = '';
    },

    click() {
      return {
        // 搜索
        handleQuery: async () => {
          this.paginationObjs.page = 1;
          this.network().getList();
        },
        // 重置
        resetQuery: async () => {
          this.queryParams = this.$options.data().queryParams;
          this.paginationObjs.page = 1;
          this.paginationObjs.limit = 10;
          this.network().getList();
        },
        // 详情
        handleDetail: async (row) => {
          this.$router.push({
            path: `${this.urlObject.routePathPrefix}detail/${row.id}`,
          });
        },
        // 导出
        handleExport: async (data) => {
          this.download(
            'cms/api/order-refund/export',
            {
              ...this.queryParams,
            },
            `售后订单列表_${new Date().getTime()}.xlsx`
          );
        },
        // 审核
        handleAudit: async (row) => {
          const rmb = this.tableData.find((item) => {
            return item.id == row.id;
          });
          this.payRmb = rmb.applyRmb;
          this.audit.auditDialog = true;
          this.audit.dialogData.id = row.id;
        },
        // 审核 - 取消 - 关闭对话框
        handleClose: async (formName) => {
          this.audit.auditDialog = false;
          this.$refs[formName].resetFields();
          this.audit.dialogData.auditStatus = '';
        },
        // 审核 - 确定 - 关闭对话框
        handleStatus: async (formName) => {
          const throttleStatus = this.throttle(); // 节流
          if (!throttleStatus) return;

          this.$refs[formName].validate((valid) => {
            if (valid) {
              const newObj = JSON.parse(JSON.stringify(this.audit.dialogData));
              newObj.auditStatus = Number(this.audit.dialogData.auditStatus);
              if (newObj.auditStatus == 1) {
                newObj.auditReason = this.audit.remarkVal;
              }
              if (newObj.auditReason == '' && newObj.auditStatus == 2) {
                this.$message({
                  message: '请填写驳回理由',
                  type: 'warning',
                });
                return;
              }
              this.network().changeStatus(newObj);
            } else {
              return false;
            }
          });
        },
        // 确认收货
        handleComfirm: async (row) => {
          this.deleteMessageBox({
            message: '是否确认收货？',
            hideTit: true,
          }).then(() => {
            this.network().handleComfirm(row);
          });
        },
      };
    },
    network() {
      return {
        getList: async () => {
          const params = this.deepCopy(this.queryParams);
          delete params.dateRange;

          const obj = {
            ...params,
            pageNum: this.paginationObjs.page,
            pageSize: this.paginationObjs.limit,
            beginTime: this.queryParams.dateRange?.[0],
            afterTime: this.queryParams.dateRange?.[1],
          };
          this.loading = true;
          try {
            const { getApiName } = this.interfaceObj;
            const data = await getApiName({
              ...obj,
              type: this.type,
            });
            this.loading = false;
            this.tableData = data.rows;
            this.paginationObjs.total = data.total;
          } catch (error) {
            this.loading = false;
          }
        },
        // 审核
        changeStatus: async (obj) => {
          const { examineApiName } = this.interfaceObj;
          const data = await examineApiName(obj);
          if (data.code == 0) {
            this.$message.success('提交成功');
            this.audit.auditDialog = false;
            this.network().getList();
            this.$refs['dialogData'].resetFields();
            this.audit.dialogData.auditStatus = '';
            this.audit.remarkVal = '';
            return false;
          }
          return this.$message.error('提交失败');
        },
        handleComfirm: async (row) => {
          const { code } = await comfirmOrder(row.id);
          if (code === 0) {
            this.$modal.msgSuccess('提交成功');
          }
          this.network().getList();
        },
      };
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-message-box__title span {
  position: relative;
  left: 37px !important;
}

::v-deep .cell {
  .el-button {
    &:last-child {
      width: 40px;
      margin-right: 10px;
    }
  }
}

::v-deep .el-select {
  width: 100%;
  .el-input {
    width: 100%;
  }
}
::v-deep .order-state-row {
  padding-left: 0;
}
::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #1890ff;
  background-color: transparent;
}
.app-container span {
  font-size: 14px;
  font-weight: bold;
  color: #606266;
}
</style>
